


import 'dart:async';

import 'package:moonplay/common/app_common.dart';
import 'package:moonplay/common/event_bus_utils.dart';
import 'package:moonplay/model/search_video_model.dart';
import 'package:moonplay/pages/common_page/common_image_page.dart';
import 'package:moonplay/pages/common_page/common_text_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:moonplay/pages/tencentplayer/test_tencent.dart';
import 'package:moonplay/utils/image_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class VideoListPage extends StatefulWidget {
  final int type;

  const VideoListPage({Key key, this.type}) : super(key: key);
  @override
  _VideoListPageState createState() => _VideoListPageState();
}

class _VideoListPageState extends State<VideoListPage>  with AutomaticKeepAliveClientMixin {
  bool get wantKeepAlive => true;
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  Future _futureBuilderFuture;
  SearchVideoModel videoListPageModel;
  int pageNo = 1;
  int pageSize = 10;
  int typeId1;
  int typeId;
  String vodClass;
  String vodYear;

  StreamSubscription _eventRefVideoList;
  var _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    init();

    _eventRefVideoList = eventBus.on<RefVideoList>().listen((event) {
      if (mounted) {
        setState(() {
          pageNo = 1;
          typeId = event.typeId;
          vodYear = event.vodYear;
        });
      }
      print("${event.type}, ${widget.type}");
      if(event.type == widget.type) {
        _scrollController.animateTo(0.0,
        duration: Duration(milliseconds: 200),
        curve: Curves.decelerate);
        initGetIndex();
      }
    });
  }

  @override
  void dispose() {
    // 记得销毁对象
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return commonFutureBuilder(
      context,
      future: _futureBuilderFuture,
      callWidget: videoListPageModel!=null ? Container(padding: EdgeInsets.only(left: ScreenUtil().getWidthPx(10), right: ScreenUtil().getWidthPx(10)), margin: EdgeInsets.only(top: ScreenUtil().getWidthPx(10)), child: refWidget(),) : Container(),
      callTap: init
    );
  }

  Widget refWidget(){
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: true,    //开启上拉加载
      child: widgetBody1(),
      onRefresh: () async {
        await initGetIndex();
        _refreshController.refreshCompleted();
      },
      onLoading: () async {
        await getLoadData();
        _refreshController.loadComplete();
      },
    );
  }

  Widget widgetBody1(){
    return NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return <Widget>[
          SliverOverlapAbsorber(
            handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
            sliver: Container()
          )
        ];
      },
      body: Container(),
    );
  }

  Widget widgetBody(){
    return GridView.builder(
      controller: _scrollController,
      itemCount: videoListPageModel.records.length,
      //SliverGridDelegateWithFixedCrossAxisCount 构建一个横轴固定数量Widget
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        //横轴元素个数
        crossAxisCount: 3,
        //纵轴间距
        mainAxisSpacing: 3.0,
        //横轴间距
        crossAxisSpacing: 3.0,
        //子组件宽高长度比例
        childAspectRatio: 0.6
      ),
      itemBuilder: (BuildContext context, int index) {
        return InkResponse(
          highlightColor: Colors.transparent,
          radius: 0,
          onTap: (){
            Get.toNamed('/VideoDetailPage', arguments: {"vodId": videoListPageModel.records[index].vodId, "typeId1": widget.type});
            // Navigator.push(context, MaterialPageRoute(
            //       builder: (context) => TestTencentPage()
            //     ));
          },
          child: Container(
            child: Stack(
              children: <Widget>[
                Container(
                  height: double.infinity,
                  child: Column(
                    children: <Widget>[
                      Container(
                        height: ScreenUtil.getInstance().screenWidth / 3 / 0.75,
                        child: Stack(
                          children: <Widget>[
                            // Container(
                            //   width: double.infinity,
                            //   height: ScreenUtil.getInstance().screenWidth / 3 / 0.75,
                            //   decoration: BoxDecoration(
                            //     borderRadius: BorderRadius.all(Radius.circular(4)),
                            //     image: 
                            //     new DecorationImage(//背景图片
                            //       image: NetworkImage(videoListPageModel.records[index].vodPic),
                            //       fit: BoxFit.cover
                            //     ),
                            //   ),
                            // ),
                            Positioned(
                              top: 0,
                              left: 0,
                              right: 0,
                              bottom: 0,
                              child: Container(
                                width: double.infinity,
                                height: ScreenUtil.getInstance().screenWidth / 3 / 0.75,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.all(Radius.circular(4)),
                                ),
                                child: loadNetworkImage(videoListPageModel.records[index].vodPic,),
                              ),
                            ),
                            Positioned(
                              bottom: 0,
                              left: 0,
                              right: 0,
                              child: Container(
                                height: ScreenUtil().getWidthPx(60),
                                alignment: Alignment.centerLeft,
                                padding: EdgeInsets.only(left: ScreenUtil().getWidthPx(10)),
                                decoration: BoxDecoration(
                                  color: Color.fromRGBO(0, 0, 0, 0.7),
                                  borderRadius: BorderRadius.only(bottomLeft: Radius.circular(4), bottomRight: Radius.circular(4))
                                ),
                                child: Cmtext('${videoListPageModel.records[index].vodRemarks}', style: TextStyle(color: Colors.white, fontSize: 11), overflow: TextOverflow.ellipsis,),
                              )
                            )
                          ],
                        ),
                      ),
                      Expanded(
                        child: Container(
                          alignment: Alignment.center,
                          child: Cmtext('${videoListPageModel.records[index].vodName}', style: TextStyle(fontSize: 13), overflow: TextOverflow.ellipsis,),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            )
          ),
        );
      }
    );
  }

  //网络初始化
  init(){
    setState(() {
      _futureBuilderFuture = initGetIndex();
    });
  }

  /**
   * 网络请求
   */
  initGetIndex() async {
    setState(() {
      pageNo = 1;
    });
    if(widget.type == 3) {
      setState(() {
        typeId = 3;
        typeId1 = null;
      });
    } else if(widget.type == 4) {
      setState(() {
        typeId = 4;
        typeId1 = null;
      });
    } else {
      setState(() {
        typeId1 = widget.type;
      });
    }
    Map<String, dynamic> postData = {
      "pageNo": pageNo,
      "pageSize": pageSize,
      "typeId1": typeId1,
      "typeId": typeId,
      "vodClass": vodClass,
      "vodYear": vodYear
    };
    var _res = await HttpUtil().request("getTypeVideoList", data: postData, need_login: false);
    // LogUtil.e(_res);
    if(_res != null && _res['code'] == 200) {
      if(mounted) {
        SearchVideoModel _list = SearchVideoModel.fromJson(_res['data']);
        if (_list.records.length > 0) {
          for (var i = 0; i < _list.records.length; i++) {
            var vodPic = _list.records[i].vodPic;
            if (vodPic != "" && vodPic.substring(0, 6) == "upload") {
              _list.records[i].vodPic = "http://app.ydecai.cn/" + _list.records[i].vodPic;
            }
          }
          setState(() {
            videoListPageModel = _list;
          });
        }
      }
    }
    return _res;
  }

  getLoadData() async {
    setState(() {
      pageNo++;
    });
    Map<String, dynamic> postData = {
      "pageNo": pageNo,
      "pageSize": pageSize,
      "typeId1": typeId1,
      "typeId": typeId,
      "vodClass": vodClass,
      "vodYear": vodYear
    };
    var _res = await HttpUtil().request("getTypeVideoList", data: postData, need_login: false);
    // LogUtil.e(_res);
    if(_res != null && _res['code'] == 200) {
      if(mounted) {
        SearchVideoModel _list = SearchVideoModel.fromJson(_res['data']);
        if (_list.records.length > 0) {
          for (var i = 0; i < _list.records.length; i++) {
            var vodPic = _list.records[i].vodPic;
            if (vodPic != "" && vodPic.substring(0, 6) == "upload") {
              _list.records[i].vodPic = "http://app.ydecai.cn/" + _list.records[i].vodPic;
            }
          }
          setState(() {
            videoListPageModel.records.addAll(_list.records);
          });
        }
      }
    } else {
      setState(() {
        pageNo--;
      });
    }
    return _res;
  }
}